import React, { useState, useEffect } from 'react'
import { Table, Popover, message, Space, Button } from 'antd'
import moment from 'moment'
import style from './Index.module.less'
import { getTableList } from './ajax'
import { awaitWrap } from '@js/tool'
import OperateBtns from './components/OperateBtns/Index'
import Common from '@js/common'

function getColumns (theme, caseDetail, editable, pDispatch, common, refreshTable) {
  const list = [
    {
      title: '收件人',
      dataIndex: 'contract',
      key: 'contract',
      render: (v, l) => {
        if (l.subject_names && v) {
          const content = (
            <div className={style.persons}>
              {(l.subject_names || '').split(',').map(li => (<div key={li}>{li}</div>))}
            </div>
          )
          return <Popover placement='top' title='当事人' content={content}><span className={style['has-agent']}>{v}</span></Popover>
        } else if (v) {
          return v
        }
        return l.structure
      }
    },
    {
      title: '送达方式',
      dataIndex: 'to_type',
      key: 'to_type',
      width: 100
    },
    {
      title: '地址',
      dataIndex: 'address',
      key: 'address',
      render: (v, l) => {
        if (l.to_type === '电子送达') {
          return <span>{l.email}</span>
        }
        if (l.islast_known_place === 1) {
          return <span>{v}<span className={style['last-one']}>最后</span></span>
        }
        return v
      }
    },
    {
      title: '联系电话',
      dataIndex: 'mobile',
      key: 'mobile'
    },
    {
      title: '送达情况',
      dataIndex: 'status',
      key: 'status',
      width: 100
    },
    {
      title: '收寄日期',
      dataIndex: 'send_datetime',
      key: 'send_datetime',
      width: 120,
      render: (v) => {
        if (v) {
          return moment(v * 1000).format('YYYY-MM-DD')
        }
      }
    },
    {
      title: '送达日期',
      dataIndex: 'arrive_datetime',
      key: 'arrive_datetime',
      width: 120,
      render: (v) => {
        if (v) {
          return moment(v * 1000).format('YYYY-MM-DD')
        }
      }
    },
    {
      title: '操作',
      dataIndex: 'other',
      key: 'other',
      render: (v, l) => {
        return <OperateBtns caseDetail={caseDetail} data={l} theme={theme} editable={editable} pDispatch={pDispatch} common={common} refreshTable={refreshTable} />
      }
    }
  ]
  if (['自定义送达', '仲裁员送达'].indexOf(theme.type) === -1) {
    list.unshift({
      title: '仲裁地位',
      dataIndex: 'action_subject',
      key: 'action_subject'
    })
  }
  return list
}

// 初始化表格数据
async function initTableData (theme, setLoading, setDataSource) {
  setLoading(true)
  const [e, d] = await awaitWrap(getTableList(theme.key))
  setLoading(false)
  if (e) {
    return message.error(e.message)
  }
  setDataSource(d)
}

// 格式化时间
function formatDate (d) {
  if (!d) { return d }
  return moment(d * 1000).format('YYYY-MM-DD')
}

// 显示送达主题完成弹框
function showFinishThemeModal (theme, dataSource, dispatch) {
  const hasSend = dataSource.some(li => ['视为送达', '送达'].indexOf(li.status) !== -1)
  if (!hasSend) {
    return message.warning('确认整体送达情况前，至少要有一条送达情况为“送达”或“视为送达”')
  }
  dispatch({ type: 'finishThemeModalVisible', data: true })
  dispatch({ type: 'currentTheme', data: theme })
}

// 渲染送达主题整体完成情况
function renderThemeFinishBlock (dataSource, theme, editable, pDispatch, refreshAddress) {
  if (!theme.complete_datetime) {
    return (
      <div className={style['btn-line']}>
        <Space>
          <Button onClick={() => refreshAddress()}>刷新地址</Button>
          <Button type='primary' onClick={() => showFinishThemeModal(theme, dataSource, pDispatch)} disabled={!editable}>整体送达情况</Button>
        </Space>
      </div>
    )
  }
  return (
    <div className={style['total-btn-line']}>
      <div className={style['total-message']}>
        <span>{theme.complete_type}</span>
        <span>{formatDate(theme.complete_datetime)}</span>
        <span>备注：{theme.complete_info || '无'}</span>
      </div>
      {/* <Button className={style.print}>批量打印</Button> */}
    </div>
  )
}

// 新增送达
function addHandle (caseDetail, theme, dispatch, refreshCurrentTableFn) {
  const { processer, processor_tel: t, processerid } = caseDetail
  const { basic } = Common.store.getState()
  const { realname, id } = basic
  const { type } = theme
  const data = {
    to_type: 'EMS',
    processer,
    processerid,
    processer_tel: t,
    sender: realname,
    senderid: id,
    send_datetime: moment(moment().format('YYYY-MM-DD')),
    arrive_datetime: moment(moment().format('YYYY-MM-DD'))
  }
  let k = 'normalModalVisible'
  if (type === '自定义送达') {
    k = 'otherModalVisible'
  } else if (type === '仲裁员送达') {
    k = 'arbitratorModalVisible'
  }
  dispatch({ type: 'currentService', data })
  dispatch({ type: 'refreshCurrentTableFn', data: refreshCurrentTableFn })
  dispatch({ type: k, data: true })
}

function Main ({ theme, editable, pDispatch, common, caseDetail, refreshAddress }) {
  const [loading, setLoading] = useState(false)
  const [dataSource, setDataSource] = useState([])
  useEffect(() => {
    initTableData(theme, setLoading, setDataSource)
  }, [theme])
  const refreshCurrentTableFn = () => initTableData(theme, setLoading, setDataSource)
  return (
    <div>
      {renderThemeFinishBlock(dataSource, theme, editable, pDispatch, refreshAddress)}
      <Table size='small' loading={loading} dataSource={dataSource} pagination={false} columns={getColumns(theme, caseDetail, editable, pDispatch, common, refreshCurrentTableFn)} />
      <div className={style['add-button']}>
        {!theme.complete_datetime ? <Button disabled={!editable} type='dashed' block onClick={() => addHandle(caseDetail, theme, pDispatch, refreshCurrentTableFn)}>+ 添加送达信息</Button> : null}
      </div>
    </div>
  )
}

export default Main
